<?php
namespace App;
use Model\MemberMod;
use Model\RecordMod;
use Model\SettingModel;
use Pub\wx\KeywordReply;
use Pub\tool\Setting as SettingCache;
use Pub\wx\Qrcode;

defined('IN_IA') or exit('Access Denied');
class SignIn extends Action
{
    private $Member = null;
    private $Record = null;  //记录

    private $_uid = 0;

    public function __construct()
    {
        parent::__construct();
        if(isset($this->_gpc["uid"])) $this->_uid = $this->_gpc["uid"];
    }


    /**
     * 获取签到二维码
     */
    public function getSignQrcode()
    {
        $_setting = SettingModel::where("uniacid",$this->_uniacid)
            ->cache(!KUYUAN_DEBUG)
            ->find();
        $_keyword = $_setting["sign_keyword"];
        if(!$_keyword){
            $_keyword = ku_random();
            $_keyword = $this->getKeyword($_keyword);
            SettingModel::where("uniacid",$this->_uniacid)
                ->update(array("sign_keyword"=>$_keyword));
        }
        $_ticket_expire = $_setting["ticket_expire"];
        if($_ticket_expire < TIMESTAMP){
            $Qrcode = new Qrcode($_keyword);
            $_scene_id = $_setting["scene_id"];
            if(!$_scene_id){
                $_qrcode = $Qrcode->create();
                SettingModel::where("uniacid",$this->_uniacid)
                    ->update(array(
                        "ticket"=>$_qrcode["ticket"],
                        "ticket_expire"=>TIMESTAMP+$_qrcode["expire_seconds"],
                        "scene_id"=>$_qrcode["scene_id"]
                    ));
            }else{
                $_qrcode = $Qrcode->update($_scene_id);
                SettingModel::where("uniacid",$this->_uniacid)
                    ->update(array(
                        "ticket"=>$_qrcode["ticket"],
                        "ticket_expire"=>TIMESTAMP+$_qrcode["expire_seconds"]));
            }
        }
        $this->_result = array(
            "status"=>"success",
            "data"=>"//mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".SettingModel::where("uniacid",$this->_uniacid)->value("ticket")
        );
        $this->result($this->_result);
    }

    /**
     * 获取签到关键字
     * @param string $_keyword 生成的关键字
     * @return string 关键字
     */
    private function getKeyword($_keyword)
    {
        $Keyword = new KeywordReply($_keyword);
        if($Keyword->testRepeat()){
            $_keyword = $_keyword.'_'.$this->_uniacid;
            return $this->getKeyword($_keyword);
        }
        $Keyword->add();
        return $_keyword;
    }

    /**
     * 签到
     * @return number >=0 签到送的积分，-1=已经签到，-2=签到失败
     */
    public function signIn()
    {
        $this->register();
        if(substr(SettingCache::get(SettingCache::SUB),0,1) > 0){
            $this->missingSign($this->_member_uid);
        }
        $_today = strtotime(date("Y-m-d",TIMESTAMP));
        $this->Record = new RecordMod();
        $_data = array("uniacid"=>$this->_uniacid,"uid"=>$this->_member_uid,"time"=>$_today);
        $_record = $this->Record->findOne($_data, array("id"));
        if($_record) return -1;
        $_data["type"] = "add";
        $_data["balance"] = $this->addBalance();
        $this->handleBalance($this->_member_uid,$_data["balance"]);
        $_result = $this->Record->insert($_data);
        if($_result){
            return $_data["balance"];
        }else{
            return -2;
        }
    }

    /**
     * 漏签处理
     * @param number $_uid 用户id
     */
    public function missingSign($_uid)
    {
        $_yesterday = strtotime(date("Y-m-d",TIMESTAMP))-86400;
        if(!$this->Record instanceof RecordMod) $this->Record = new RecordMod();
        $_records = $this->Record->findAll(
            array("uniacid"=>$this->_uniacid,"uid"=>$_uid),
            array("limit"=>array(0,1),"order"=>array("id","desc")),
            array("time")
        );
        if(count($_records) > 0){
            $_finally_time = $_records[0]["time"];
            $i = ($_yesterday - $_finally_time) / 86400;
            $j = 1;
            $_sub_balance = 0;
            $_data =  array(
                "uniacid"=>$this->_uniacid,
                "uid"=>$_uid,
                "type"=>"sub"
            );
            $_user_balance = $this->getBalance($_uid);
            for(;$i>0;$i--,$j++){
                $_data["time"] = $_finally_time + (86400*$j);
                $_balance = $this->subBalance();
                $_sub_balance += $_balance;
                if($_user_balance - $_sub_balance < 0){
                    $_balance = 0;
                }
                $_data["balance"] = $_balance;
                $this->Record->insert($_data);
            }
            $this->handleBalance($_uid,$_sub_balance,"sub");
        }
    }

    /**
     * 签到注册
     * @return bool|mixed
     */
    private function register()
    {
        $this->Member = new MemberMod();
        $_data = array("uniacid"=>$this->_uniacid,"uid"=>$this->_member_uid);
        $_member = $this->Member->findOne($_data,array("id"));
        $_result = false;
        if(!$_member) {
            $_result = $this->Member->insert($_data);
        }
        return $_result;
    }

    /**
     * 获取签到新增积分
     */
    private function addBalance()
    {
        $_add = SettingCache::get(SettingCache::ADD);
        $_add = explode(",",$_add);
        if(count($_add) == 1){
            $_balance = $_add[0];
        }else{
            $_balance = mt_rand($_add[0],$_add[1]);
        }
        return $_balance;
    }

    /**
     * 扣除的积分
     */
    private function subBalance()
    {
        $_sub = SettingCache::get(SettingCache::SUB);
        $_sub = explode(",",$_sub);
        if(count($_sub) == 1){
            $_balance = $_sub[0];
        }else{
            $_balance = mt_rand($_sub[0],$_sub[1]);
        }
        return $_balance;
    }

    /**
     * 获取签到记录
     * @param number uid 用户id
     */
    public function getSignRecord()
    {
        $this->Record = new RecordMod();
        $_record = $this->Record->findAll(
            array(
                "uniacid"=>$this->_uniacid,
                "uid"=>$this->_uid
            ),
            array(
                "limit"=>$this->_gpc["limit"],
                "order"=>array("id","desc")
            ),
            array("time","type","balance")
        );
        if(count($_record) > 0){
            foreach($_record as $_k=>$_v){
                $_record[$_k]["time"] = date("Y-m-d",$_v["time"]);
            }
            $this->_result = array("status"=>"success","data"=>$_record);
        }
        $this->result($this->_result);
    }
}